<template>
  <div class="add">
    <!-- 面包屑导航 -->
    <breadcrumb firstTitle="商品管理" secondTitle="添加商品"></breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- alert警告区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>

      <!-- step步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称：" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格：" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品重量：" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品数量：" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类：" prop="goods_cat">
              <el-cascader :options="cateList" :props="cateProps" v-model="addForm.goods_cat" @change="handleChange"></el-cascader>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="items.attr_name" v-for="items in manyTableData" :key="items.attr_id">
              <el-checkbox-group v-model="items.attr_vals">
                <el-checkbox :label="item" v-for="(item,indey) in items.attr_vals" :key="indey" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" prop="name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示图片要提交到的后台地址 -->
            <el-upload class="upload-demo" :action="imageURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headerObj" :on-success="successHandle">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
        <!-- 预览图片dialog对话框 -->
        <el-dialog title="预览图片" :visible.sync="previewVisble" width="50%" class="previewImg">
          <img :src="previewPath" alt="">
        </el-dialog>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import breadcrumb from '../../breadcurmb/BreakCrumb.vue'
import request from '../../../network/request'
import { goodsAddFormRulesMixin } from '@/common/mixin'

export default {
  name: 'MyAdd',
  mixins: [goodsAddFormRulesMixin],
  components: {
    breadcrumb
  },
  created() {
    this.getCartList()
  },
  computed: {
    nextGoTag() {
      return (this.addForm.goods_name !== '' && this.addForm.goods_price !== '' && this.addForm.goods_weight !== '' && this.addForm.goods_number !== '' && this.addForm.goods_cat.length !== 0)
    },
    // 计算在基本信息中选中的三级分类id
    isselectId() {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  },
  data() {
    return {
      // step步骤条默认激活项
      activeIndex: 0,
      // 存放tags标签页里面表单的值
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        // 服务器存储图片的地址
        pic: [],
        // 商品介绍
        introduce: '',
        attr: []
      },
      // 表单规则
      // addFormRules: {
      //   // 名称
      //   goods_name: [
      //     { required: true, message: '请输入商品名称', trigger: 'blur' }
      //   ],
      //   // 价格
      //   goods_price: [
      //     { required: true, message: '请输入商品价格', trigger: 'blur' }
      //   ],
      //   // 重量
      //   goods_weight: [
      //     { required: true, message: '请输入商品重量', trigger: 'blur' }
      //   ],
      //   // 数量
      //   goods_number: [
      //     { required: true, message: '请输入商品数量', trigger: 'blur' }
      //   ],
      //   // 分类
      //   goods_cat: [
      //     { required: true, message: '请选中商品分类', trigger: 'blur' }
      //   ]
      // },
      // 商品列表数据
      cateList: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 动态参数列表数据
      manyTableData: [],
      // 静态属性列表数据
      onlyTableData: [],
      // 上传图片的url地址
      imageURL: 'https://lianghj.top:8888/api/private/v1/upload',
      // 设置上传的请求头部
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片的地址
      previewPath: '',
      // 预览图片的dialog对话框的显示与隐藏
      previewVisble: false,
      // 由addForm深拷贝下来的对象
      newAddForm: {}
    }
  },
  methods: {
    // 获取添加商品的数据
    async getCartList() {
      const { data: res } = await request('categories')

      if (res.meta.status !== 200) return this.$message.error('商品列表获取失败')

      this.cateList = res.data
    },
    // 当级联选择器有选中的值时触发
    handleChange() {
      // addForm.goods_cat选中的是选中项的id值
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 点击标签页切换时自动触发
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.nextGoTag === false) {
        this.$message.error('请填写完整商品信息')
        return false
      }
    },
    // 点击tag按钮触发
    async tabClick() {
      if (this.activeIndex === '1') {
        const { data: res } = await request(`categories/${this.isselectId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取商品参数列表失败')

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })
        this.manyTableData = res.data
      }
      else if (this.activeIndex === '2') {
        const { data: res } = await request(`categories/${this.isselectId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取商品属性列表失败')
        this.onlyTableData = res.data
      }
    },
    // 点击图片预览时触发
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewVisble = true
    },
    // 移除图片时触发
    handleRemove(file) {
      // 要移除的文件路径
      const deletePath = file.response.data.tmp_path
      // 查找要移除的文件路径在pic中的索引值
      const index = this.addForm.pic.findIndex(item => item.tmp_path === deletePath)
      // 根据索引值移除
      this.addForm.pic.splice(index, 1)
    },
    // 图像文件上传成功时调用
    successHandle(response) {
      const picPath = {
        pic: response.data.tmp_path
      }
      this.addForm.pic.push(picPath)
    },
    // 添加商品
    async add() {
      // 深拷贝
      this.newAddForm = JSON.parse(JSON.stringify(this.addForm))
      // 将数组变成字符串
      this.newAddForm.goods_cat = this.newAddForm.goods_cat.join(',')

      this.manyTableData.forEach(item => {
        const manyParam = {
          attr_id: item.attr_id,
          // 将动态参数中的attr_value数组转换成字符串
          attr_value: item.attr_vals.join(',')
        }
        this.newAddForm.attr.push(manyParam)
      })
      this.onlyTableData.forEach(item => {
        const onlyParam = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.newAddForm.attr.push(onlyParam)
      })
      const { data: res } = await request.post('goods', this.newAddForm)
      if (res.meta.status !== 201) return this.$message.error('商品添加失败')

      this.$message.success('商品添加成功')
      this.$router.push('/goods')
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 25px 0;
}

/deep/ .el-step__title {
  font-size: 14px;
}
.el-checkbox {
  margin: 0;
  margin: 0 20px 0 0;
}
.previewImg img {
  width: 100%;
}
.el-button {
  margin-top: 15px;
}
</style>